package com.shen.demo.demos.web.compont.webSocket;

import java.net.InetSocketAddress;
import java.security.SecureRandom;
import java.util.Map;

import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

@Component
public class MyInterceptor implements HandshakeInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(HandshakeInterceptor.class);

    /**
     * 握手前
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        logger.info("握手开始");

        InetSocketAddress remoteAddress = request.getRemoteAddress();
        /*if (remoteAddress == null) {
            logger.warn("无法获取远程地址");
            return false;
        }*/
        String hostName = remoteAddress.getHostName();
        SecureRandom secureRandom = new SecureRandom();
        String sessionId = hostName + secureRandom.nextInt(1000);

        // 使用 ServletServerHttpRequest 获取查询参数
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            String whareaId = servletRequest.getServletRequest().getParameter("whareaId");
            if (Strings.isNotBlank(whareaId)) {
                attributes.put("whareaId", whareaId);
            } else {
                logger.warn("未提供 whareaId 参数");
                return false;
            }
        } else {
            logger.warn("请求类型不支持获取查询参数");
            return false;
        }
        if (Strings.isNotBlank(sessionId)) {
            attributes.put("session_id", sessionId);
            logger.info("用户 session_id {} 握手成功！", sessionId);
            return true;
        }

        logger.warn("用户登录已失效");
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        if (exception != null) {
            logger.error("握手失败: {}", exception.getMessage(), exception);
        }
    }
}



